package com.fac.service.impl;

import com.fac.constant.ExceptionConstant;
import com.fac.dto.InspectionRecordCreateDTO;
import com.fac.entity.Equipment;
import com.fac.entity.InspectionPlan;
import com.fac.entity.InspectionRecord;
import com.fac.exception.BusinessException;
import com.fac.mapper.EquipmentMapper;
import com.fac.mapper.InspectionPlanMapper;
import com.fac.mapper.InspectionRecordMapper;
import com.fac.service.InspectionRecordService;
import com.fac.vo.InspectionRecordCreateVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
public class InspectionRecordServiceImpl implements InspectionRecordService {

    @Autowired
    private InspectionRecordMapper inspectionRecordMapper;

    @Autowired
    private InspectionPlanMapper inspectionPlanMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @Transactional
    public InspectionRecordCreateVO create(InspectionRecordCreateDTO createDTO) {
        // 查询巡检计划
        InspectionPlan plan = inspectionPlanMapper.selectById(createDTO.getPlanId());
        if (plan == null) {
            throw new BusinessException(ExceptionConstant.INSPECTION_PLAN_NOT_FOUND);
        }

        // 查询设备信息
        Equipment equipment = equipmentMapper.selectById(createDTO.getEquipmentId());
        if (equipment == null) {
            throw new BusinessException(ExceptionConstant.EQUIPMENT_NOT_FOUND);
        }

        try {
            // 创建巡检记录
            InspectionRecord record = InspectionRecord.builder()
                    .planId(createDTO.getPlanId())
                    .equipmentId(createDTO.getEquipmentId())
                    // TODO: 从当前登录用户获取
                    .inspectorId(1L)
                    .result(objectMapper.writeValueAsString(createDTO.getResult()))
                    .abnormalDescription(createDTO.getAbnormalDescription())
                    .handlingSuggestions(createDTO.getHandlingSuggestions())
                    .inspectionTime(LocalDateTime.now())
                    .build();

            // 保存记录
            inspectionRecordMapper.insert(record);

            // 返回结果
            return InspectionRecordCreateVO.builder()
                    .recordId(record.getRecordId())
                    .inspectionTime(record.getInspectionTime())
                    .build();
        } catch (JsonProcessingException e) {
            log.error("巡检结果序列化失败", e);
            throw new BusinessException(ExceptionConstant.INSPECTION_RESULT_FORMAT_ERROR);
        }
    }
} 